<template>
  <div class="zh-taped">
    <nav-header></nav-header>
    <transition name="fade" mode="out-in">
      <div class="zh-table">
        <div class="zh-table-open clear">
          <div class="zh-open-left fl">
            <div class="open-width" style="width: 180px" v-if="$store.state.platformInformation">
              <el-cascader v-model="app_code" v-if="isTopEducation" placeholder="选择教育局/学校" :options="educationCodeData"
                :props="Props" :show-all-levels="false" clearable></el-cascader>
              <el-select v-else v-model="app_code" filterable placeholder="选择教育局/学校">
                <el-option v-for="item in schoolcodeData" :key="item.app_code" :label="item.name" :value="item.app_code">
                </el-option>
              </el-select>
            </div>
            <div class="open-width" style="width: 220px">
              <el-input v-model="keyword" placeholder="请输入设备名搜索" @keyup.enter.native="searchFunc"></el-input>
            </div>
            <el-button type="primary" @click="searchFunc">搜索</el-button>
            <el-button type="primary" @click="reset">重置</el-button>
          </div>
          <div class="zh-open-right fr">
            <el-button type="primary" @click="reBoot()">重启流媒体服务</el-button>
            <el-button type="primary" @click="saveBox()">新增</el-button>
            <el-button type="danger" @click="deleteMuilt_confirm">批量删除</el-button>
          </div>
        </div>
        <div class="zh-table-contents" v-loading="loading.status" :element-loading-text="loading.txt"
          v-loading.fullscreen.lock="loading.full">
          <el-table v-if="$store.state.checkLevel" :data="listData" border @selection-change="tableSelectionChange"
            max-height="600" style="width: 100%">
            <el-table-column type="selection" width="50" align="center" fixed></el-table-column>
            <el-table-column prop="platform_name" label="组织架构" sortable align="center" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="name" label="设备名" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop label="类型" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                <div v-html="getType(scope.row.type)"></div>
              </template>
            </el-table-column>
            <el-table-column prop="class_name" label="校园分区" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop="ip" label="IP" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop="stream_addr" label="流名称" align="center" min-width="240" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="comment" label="注释" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop label="状态" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                <div v-html="getStatus(scope.row.status)"></div>
              </template>
            </el-table-column>
            <el-table-column prop label="操作" align="center" width="270">
              <template slot-scope="scope">
                <el-button @click="videoView(scope.row)" type="text">预览</el-button>
                <template v-if="parseInt(scope.row.status) === 2">
                  <el-button @click="change_confirm(scope.row, 1)" type="text">启用</el-button>
                </template>
                <template v-if="parseInt(scope.row.status) === 1">
                  <el-button @click="change_confirm(scope.row, 2)" type="text">禁用</el-button>
                </template>
                <el-button @click="saveBox(scope.row)" type="text">编辑</el-button>
                <el-button @click="delete_confirm(scope.row)" type="text" class="delete-button">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-table v-else :data="listData" border @selection-change="tableSelectionChange" max-height="600"
            style="width: 100%">
            <el-table-column type="selection" width="50" align="center" fixed></el-table-column>
            <el-table-column prop="name" label="设备名" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop label="类型" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                <div v-html="getType(scope.row.type)"></div>
              </template>
            </el-table-column>
            <el-table-column prop="class_name" label="校园分区" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop="ip" label="IP" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop="stream_addr" label="流名称" align="center" min-width="300" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="comment" label="注释" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop label="状态" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                <div v-html="getStatus(scope.row.status)"></div>
              </template>
            </el-table-column>
            <el-table-column prop label="操作" align="center" width="280">
              <template slot-scope="scope">
                <el-button @click="videoView(scope.row)" type="text">预览</el-button>
                <template v-if="parseInt(scope.row.status) === 2">
                  <el-button @click="change_confirm(scope.row, 1)" type="text">启用</el-button>
                </template>
                <template v-if="parseInt(scope.row.status) === 1">
                  <el-button @click="change_confirm(scope.row, 2)" type="text">禁用</el-button>
                </template>
                <el-button @click="saveBox(scope.row)" type="text">编辑</el-button>
                <el-button @click="delete_confirm(scope.row)" type="text" class="delete-button">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="table-pagination" v-show="total_number > 10">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
              :current-page="listParam.page_index" :page-sizes="[10, 20, 30, 40, 50, 100]"
              :page-size="listParam.page_size" layout="total, sizes, prev, pager, next, jumper" :total="total_number">
            </el-pagination>
            <div class="pagination-button">
              <el-button @click="getList" type="primary" icon="el-icon-refresh" circle title="刷新数据" size="mini">
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </transition>

    <transition name="el-fade-in-linear">
      <div class="masking" :class="{ activeLive: isActive }">
        <div class="maskingBox">
          <div class="masking_h">
            <span>直播预览</span>
            <i class="el-icon-close" @click="viewClose"></i>
          </div>
          <div class="masking_c">
            <!-- <flvPlayer v-if="showVideoPlayer" id="flvPlayer" :playerOption.sync="playerOption"></flvPlayer> -->
            <flvdplayer v-if="showVideoPlayer" :playerOption.sync="playerOption"></flvdplayer>
          </div>
        </div>
      </div>
    </transition>
    <!-- 新增设备 -->
    <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" :title="equipmentTxt ? '编辑设备' : '新增设备'"
      :visible.sync="NewEquipment" width="400px">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" status-icon label-width="85px" class="demo-ruleForm">
        <el-form-item label="设备名" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入设备名" :maxlength="parseInt(20)" clearable></el-input>
        </el-form-item>
        <el-form-item v-if="$store.state.checkLevel" label="所属架构" prop="app_code">
          <el-cascader v-model="ruleForm.app_code" style="width: 100%" v-if="isTopEducation" placeholder="教育局/学校"
            :options="educationCodeData" :props="Props" :show-all-levels="false" @change="getAllappcode" clearable>
          </el-cascader>
          <el-select v-else v-model="ruleForm.app_code" @change="getValue" filterable placeholder="教育局/学校">
            <el-option v-for="item in schoolcodeData" :key="item.app_code" :label="item.name" :value="item.app_code">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属分区" prop="classroom_id">
          <el-select filterable v-model="ruleForm.classroom_id" placeholder="请选择所属分区">
            <el-option-group v-for="group in partitionData" :key="group.label" :label="group.label">
              <el-option v-for="item in group.options" :key="item.id" :label="item.name" :value="item.id"
                :disabled="item.level == 1"></el-option>
            </el-option-group>
          </el-select>
        </el-form-item>
        <el-form-item label="IP" prop="ip">
          <el-input v-model="ruleForm.ip" placeholder="请输入IP地址" :maxlength="parseInt(15)" clearable></el-input>
        </el-form-item>
        <el-form-item label="流名称" prop="stream_addr">
          <el-input v-model="ruleForm.stream_addr" :minlength="parseInt(6)" :maxlength="parseInt(200)"
            placeholder="请输入流名称"></el-input>
        </el-form-item>
        <el-form-item label="注释">
          <el-input v-model="ruleForm.comment" placeholder="请输入注释(不超过50个字符)" :maxlength="parseInt(50)" clearable>
          </el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="ruleForm.status">
            <el-radio label="1">启用</el-radio>
            <el-radio label="2">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelForm">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
// import flvPlayer from "../../public/flvPlayer";
import flvdplayer from "@/components/public/flvdplayer";
export default {
  data() {
    var validateAddr = (rule, value, callback) => {
      let reg = /^[0-9a-zA-Z]+$/;
      if (value === "") {
        callback(new Error("请输入流名称"));
      } else if (value.toString().length < 6 || value.toString().length > 200) {
        callback(new Error("名称长度为6~200个字符哦"));
      } else if (!reg.test(value)) {
        callback(new Error("名称必须是数字或者字母"));
      } else {
        callback();
      }
    };
    return {
      isTopEducation:
        sessionStorage.getItem("CheckSchoolAppCode") ==
        "00000000000000000000000000000000",
      topApp_code: sessionStorage.getItem("CheckSchoolAppCode"),
      educationCodeData: [],
      classRoom: [],
      nonClassRoom: [],
      app_code: "",
      Props: {
        value: "app_code",
        label: "name",
        checkStrictly: true,
      },
      schoolcodeData: "",
      equipmentTxt: null,
      loading: {
        status: false,
        txt: "获取数据...",
        full: false,
      },
      isActive: true,
      listData: [],
      listParam: {
        keyword: "",
        type: 3,
        page_index: 1,
        page_size: 10,
        app_code: "",
      },
      keyword: "",
      total_number: 0,
      selected: [],
      statusArr: { 1: "启用", 2: "停用" },

      liveUrl: "",
      typeArr: {
        0: "0620",
        1: "0600B",
        2: "0650",
        3: "rtmp",
        4: "rtsp",
        5: "奥威亚",
        6: "网动",
        7: "中庆",
        8: "锐取",
        9: "0683",
        10: "0660",
      },
      NewEquipment: false,
      ruleForm: {
        id: 0,
        name: "",
        classroom_id: "", //所属教室
        ip: "",
        stream_addr: "",
        comment: "", //注释
        status: "1",
        app_code: "",
        // type: '',
      },
      rules: {
        name: [
          { validator: this.validateName, trigger: "blur", required: true },
        ],
        stream_addr: [
          { required: true, validator: validateAddr, trigger: "blur" },
        ],
        classroom_id: [
          { validator: this.checkChange, trigger: "change", required: true },
        ],
        app_code: [
          { trigger: "change", message: "请选择组织架构", required: true },
        ],
        ip: [{ validator: this.validateIP, trigger: "blur", required: true }],
      },
      classroomData: [],
      partitionData: [],
      statusArr: {
        1: "启用",
        2: "禁用",
      },

      showVideoPlayer: false,
      playerOption: { type: "flv", url: "" },
    };
  },
  created() {
    this.getList();
    this.getLiveUrl();
    this.toggleView();
    this.getClassroomData();
    this.get_educationData();
    this.get_schoolcode();
  },
  watch: {
    $route() {
      this.toggleView();
    },
    NewEquipment() {
      if (this.NewEquipment === false) this.$refs.ruleForm.resetFields();
    },
  },
  mounted() {
    this.stayLoadingTimeOut = setInterval(() => {
      this.checkStayLoading();
    }, 15000);
  },
  methods: {
    get_schoolcode() {
      /*获取学校教育局 */
      let params = {
        app_code: sessionStorage.getItem("CheckSchoolAppCode"),
        updown: "down",
        is_include_myself: 1,
      };
      let success = (res) => {
        // console.log(res, 'pppp')
        this.schoolcodeData = res.data;
      };
      // if(isTopEducation){
      // 	this.$ajax.get('api/newlevel/levelorg_list', {params, func: {success}})
      // }
      this.$ajax.get("api/newlevel/get_updown_platform", {
        params,
        func: { success },
      });
    },
    get_educationData() {
      // 最高教育局获取所有教育局/学校
      let params = {
        type: 1,
        is_havemyself: 1,
      };
      let success = (res) => {
        console.log(res.data, 555);
        this.educationCodeData = res.data;
      };
      this.$ajax.get("api/newlevel/levelorg_list", {
        params,
        func: { success },
      });
    },
    getValue(val) {
      console.log(val);
      this.ruleForm.classroom_id = null;
      this.partitionData = [];
      this.getClassroomData(val);
    },
    getAllappcode(val) {
      this.ruleForm.classroom_id = null;
      this.partitionData = [];
      this.getClassroomData(val[val.length - 1]);
    },
    getLiveUrl() {
      let success = (data) => {
        this.liveUrl = data.data;
      };
      this.$ajax.get("api/recorder/live_url", { func: { success: success } });
    },
    searchFunc() {
      this.listParam.app_code = this.app_code[this.app_code.length - 1];
      this.listParam.keyword = this.keyword;
      this.listParam.page_index = 1;
      this.getList();
    },
    reset() {
      this.app_code = "";
      this.keyword = "";
      this.listParam = {
        keyword: "",
        type: 3,
        page_index: 1,
        page_size: 10,
        app_code: "",
      };
      this.getList();
    },
    getNameString(val) {
      return val.split("?")[0];
    },
    saveBox(obj) {
      this.equipmentTxt = obj;
      if (!is_empty(obj)) {
        this.ruleForm.id = obj.id;
        this.ruleForm.name = obj.name;
        this.ruleForm.classroom_id = obj.classroom_id ? obj.classroom_id : null;
        this.ruleForm.ip = obj.ip;
        this.ruleForm.comment = obj.comment;
        this.ruleForm.status = obj.status.toString();
        this.ruleForm.stream_addr = this.getNameString(
          obj.stream_addr.toString()
        );
      } else {
        this.ruleForm = {
          id: 0,
          name: "",
          classroom_id: "", //所属教室
          ip: "",
          comment: "", //注释
          status: "1",
          stream_addr: "",
        };
      }
      this.NewEquipment = true;
    },
    saveRecorder() {
      this.loading.txt = "正在保存...";
      this.loading.status = true;
      this.loading.full = true;
      let success = (data) => {
        this.NewEquipment = false;
        this.loading.status = false;
        this.loading.full = false;
        this.loading.txt = "获取数据...";
        this.$message.success(data.msg);
        this.cancelForm();
        this.getList();
      };
      let fail = (data) => {
        this.loading.status = false;
        this.loading.full = false;
        this.loading.txt = "获取数据...";
        let msg = "";
        if (typeof data.msg == "object") {
          for (var i = 0; i <= data.msg.length - 1; i++) {
            msg +=
              '<p style="line-height:20px;color:#f56c6c">' +
              data.msg[i] +
              "</p>";
          }
        } else {
          msg = data.msg;
        }

        this.$message.error(data.msg);
      };
      this.ruleForm.type = 3;
      if (this.$store.state.checkLevel) {
        this.ruleForm.app_code =
          this.ruleForm.app_code[this.ruleForm.app_code.length - 1];
      }
      if (parseInt(this.ruleForm.id) > 0) {
        this.$ajax.put("api/recorder/recorder", this.ruleForm, {
          func: { success: success, fail: fail },
        });
      } else {
        this.$ajax.post("api/recorder/recorder", this.ruleForm, {
          func: { success: success, fail: fail },
        });
      }
    },
    cancelForm() {
      this.NewEquipment = false;
      this.$refs["ruleForm"].resetFields();
    },
    change_confirm(obj, status) {
      let yes = (data) => {
        this.change(obj.id, status);
      };
      let cancel = (data) => { };
      this.e_confirm({
        yes: yes,
        cancel: cancel,
        txt:
          "确定将 " +
          obj.name +
          " 设置为 " +
          this.statusArr[parseInt(status)] +
          " 吗？",
      });
    },
    change(id, status) {
      let success = (data) => {
        this.$message.success(data.msg);
        this.getList();
      };
      this.$ajax.post(
        "api/recorder/recorder_data_status",
        { id: id, status: status },
        { func: { success: success } }
      );
    },
    getClassroomData(app_code) {
      let success = (data) => {
        if (this.$store.state.checkLevel) {
          if (data.data[0].length == 0) {
            this.classRoom = data.data[1]; // .filter(i =>{ return i.level == 2})
            this.nonClassRoom = data.data[0];
          } else if (data.data[0][0].type === 1) {
            this.classRoom = data.data[0];
            this.nonClassRoom = data.data[1];
          } else {
            this.classRoom = data.data[1];
            this.nonClassRoom = data.data[0];
          }
        } else {
          data.data.forEach((item) => {
            item.children.forEach((val) => {
              if (val.type === 1) {
                this.classRoom.push(val);
              } else if (val.type === 0) {
                this.nonClassRoom.push(val);
              }
            });
          });
        }

        let res1 = {
          label: "教室分区",
          options: this.classRoom,
        };
        let res2 = {
          label: "非教室分区",
          options: this.nonClassRoom,
        };
        this.partitionData.push(res1, res2);
      };
      if (this.$store.state.checkLevel) {
        let params = {
          app_code: app_code,
        };
        this.$ajax.get("api/school/platform_get_inspection", {
          params,
          func: { success: success },
        });
      } else {
        this.$ajax.get("api/school/inspection_data", {
          func: { success: success },
        });
      }
    },

    submitForm() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.saveRecorder();
        } else {
          return false;
        }
      });
    },
    //验证
    validateName(rule, value, callback) {
      if (value === "") {
        return callback(new Error("请输入设备名称"));
      } else if (!validateName(value)) {
        return callback(new Error("请不要输入空格字符"));
      } else {
        callback();
      }
    },
    validateStream(rule, value, callback) {
      if (!validateName(value)) {
        return callback(new Error("请不要输入空格字符"));
      } else {
        callback();
      }
    },
    validateNotes(rule, value, callback) {
      if (value === "") {
        return callback(new Error("请输入注释"));
      } else if (!validateName(value)) {
        return callback(new Error("请不要输入空格字符"));
      } else {
        callback();
      }
    },
    validateIP(rule, value, callback) {
      if (value === "") {
        return callback(new Error("请输入IP地址"));
      } else if (!validateIp(value)) {
        return callback(new Error("请输入正确的IP地址"));
      } else {
        callback();
      }
    },
    checkChange(rule, value, callback) {
      if (!isEmpty(value)) {
        return callback(new Error("请选择所属分区"));
      } else {
        callback();
      }
    },

    selectChange(obj) {
      var inx = obj.$index;
      var code = obj.row.recorder_status;
      this.recorderTransfer(inx, code);
    },
    viewClose() {
      this.showVideoPlayer = false;
      this.isActive = true;
    },
    videoView(item) {
      this.showVideoPlayer = true;
      this.playerOption.url = item.play_url;
      this.isActive = false;
    },
    //如果开机或重启超过4分钟将不会再持续获取设备状态
    checkStayLoading() {
      if (this.stayLoadingInx.length > 0) {
        for (var i = this.stayLoadingInx.length - 1; i >= 0; i--) {
          let inx = this.stayLoadingInx[i].inx;
          if (Number(new Date()) - this.stayLoadingInx[i].times > 240 * 1000) {
            this.stayLoadingInx.splice(i, 1);
          }
          this.getRecorderStatus(inx);
        }
      }
    },
    getType(val) {
      return this.typeArr[parseInt(val)];
    },
    getStatus(val) {
      return this.statusArr[parseInt(val)];
    },
    //选中
    tableSelectionChange(val) {
      this.selected = val;
    },
    getList() {
      this.loading.status = true;
      let success = (data) => {
        this.loading.status = false;
        this.stayLoadingInx = [];
        this.listData = data.data.data;
        this.total_number = data.data.data_sum;
      };
      let fail = (data) => {
        this.loading.status = false;
        this.$message.error(data.msg);
      };
      //执行请求，并将回调方法变成config成员以便鉴权过期可以执行
      this.$ajax.get("api/recorder/recorder_list", {
        params: this.listParam,
        func: { success: success, fail: fail },
      });
    },

    delete(id) {
      let success = (data) => {
        this.$message.success(data.msg);
        this.getList();
      };
      this.$ajax.delete("api/recorder/recorder", {
        params: { id: id },
        func: { success: success },
      });
    },
    delete_confirm(obj) {
      let yes = (data) => {
        this.delete(obj.id);
      };
      let cancel = (data) => { };
      this.e_confirm({
        yes: yes,
        cancel: cancel,
        txt: "确定将 " + obj.name + " 删除吗？",
      });
    },
    deleteMuilt_confirm() {
      if (this.selected.length === 0) {
        this.$message.warning("请选择要删除的设备");
        return false;
      }
      let yes = (data) => {
        this.muilDelete();
      };
      let cancel = (data) => { };
      this.e_confirm({
        yes: yes,
        cancel: cancel,
        txt: "确定要删除选中的设备吗？",
      });
    },
    muilDelete() {
      var ids = [];
      for (var i = this.selected.length - 1; i >= 0; i--) {
        ids.push(this.selected[i].id);
      }
      this.delete(ids);
    },
    handleSizeChange(val) {
      this.listParam.page_index = 1;
      this.listParam.page_size = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listParam.page_index = val;
      this.getList();
    },

    //记录导航状态
    toggleView() {
      this.view = this.$route.name;
    },
    reBoot() {
      let yes = (data) => {
        let success = (data) => {
          this.$message.success("重启流媒体服务成功，请稍后~");
        };
        this.$ajax.get("api/recorder/restart_type_server", {
          params: {
            type: 3,
          },
          func: { success: success },
        });
      };
      let cancel = (data) => { };
      this.e_confirm({
        yes: yes,
        cancel: cancel,
        txt: "确定重启流媒体服务吗？",
      });
    },
  },
  //离开页面之前
  beforeRouteLeave(to, from, next) {
    clearInterval(this.stayLoadingTimeOut);
  },
  beforeDestroy() {
    clearInterval(this.stayLoadingTimeOut);
  },
  components: {
    // flvPlayer,
    flvdplayer,
  },
};
</script>
<style lang="scss">
.zh-taped {
  .el-table__body-wrapper table tbody {
    td:nth-child(8) {
      padding: 0;
    }

    .el-loading-mask {
      height: 40px;
      line-height: 40px;

      .el-loading-spinner {
        margin-top: -20px;
        height: 40px;
        line-height: 40px;

        .circular {
          height: 32px;
          line-height: 32px;
        }
      }
    }
  }
}

.masking {
  display: block;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  transition: 0.5s;
  background: rgba(0, 0, 0, 0.3);
  z-index: 4;

  .maskingBox {
    position: absolute;
    top: 20%;
    left: 50%;
    width: 800px;
    margin-left: -400px;
    background: #fff;
  }

  .masking_h {
    padding: 10px 15px;
    background: #348efc;
    text-align: center;
    text-align-last: justify;

    >span,
    >i {
      font-size: 16px;
      text-align-last: initial;
      display: inline-block;
      vertical-align: middle;
      color: #fff;
    }

    >i {
      cursor: pointer;
    }
  }

  .masking_c {
    padding: 15px;
    height: 450px;
  }
}

.activeLive {
  opacity: 0;
  visibility: hidden;
}
</style>
